package relu.fbs.jfm;

import java.util.*;
import java.lang.*;
import java.io.*;

import relu.fbs.BadDataException;

/** Holds the time series data for a collection of farms */
public class JFMTimeSeries {
	public final HashMap<Integer,JFMFarmTimeSeries> data = new HashMap<Integer,JFMFarmTimeSeries>();
	private static int minNumInAverage=3;
	public void addFarm(JFMFarmData fdat,int year) throws BadDataException {
		if ( !data.containsKey(fdat.farmId)){				
			data.put(fdat.farmId, new JFMFarmTimeSeries(fdat.farmId));
		}
		data.get(fdat.farmId).addYear(fdat, year);
	}
	
	public void exportTimeAverageToCSV(String fileName,int firstYr,int lastYr) throws BadDataException, IOException {
		FileWriter writer=new FileWriter(fileName);
		writer.write(JFMFarmData.allToCSVHeader());
		int numMissed=0;
		int numRetained=0;
		for ( JFMFarmTimeSeries tser:data.values()){
			JFMFarmDataTSAv avdat=tser.getAverage(firstYr,lastYr);
			if ( avdat != null ){
				if ( avdat.numInAverage() >= minNumInAverage ){
					numRetained++;
					avdat.writeAllToCSV(writer);
				} else {
					// Not enough data again
					numMissed++;
				}
			} else {				
				// Insufficient data for this farm over the period 
				numMissed++;
			}
		}
		System.out.println("Missed "+numMissed+" farms and kept "+numRetained+" in this average");
	}
	
	public void exportToDirectory(String dirname,int minYears) throws IOException, BadDataException {
//		Runtime rt = Runtime.getRuntime();
//		rt.exec("mkdir "+dirname);
		for ( JFMFarmTimeSeries tser:data.values()){
			if ( tser.years.size() >= minYears ){
				tser.exportYearsToCSV(dirname);
			}
		}
	}
	public void exportToCSV(int minYears) throws IOException, BadDataException {

		FileWriter writer=new FileWriter("ts.csv");
		writer.write("Year,"+JFMFarmData.allToCSVHeader());
		for ( JFMFarmTimeSeries tser:data.values()){
			writer.write(tser.printYearsToCSV());
		}
		writer.close();
	}
	

}
